package com.example.blog.aspect;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Aspect
@Component
public class LogAspect {
    @Pointcut("execution(* com.example.blog.controller..*.*(..))")
    public void log(){}
    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString();
        String ip = request.getRemoteAddr();
        String classMethod =  joinPoint.getSignature().getDeclaringTypeName()+":"+joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        RequestLog requestLog = new RequestLog(url, ip, classMethod, args);

        log.info("Request : {}", requestLog);
    }
    @After("log()")
    public void doAfter(){}
    @AfterReturning(returning = "res", pointcut = "log()")
    public void doAfterRuturn(Object res){
        log.info("Object {}", res);
    }
    @AllArgsConstructor
    @NoArgsConstructor
    @Data
    @ToString
    private class RequestLog{
        String url;
        String ip;
        String classMethod;
        Object[] args;
    }
}
